﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;

namespace BLL.BusinessClasses
{
    public sealed class Email
    {
        private readonly static SmtpClient DefaultSMTPClient;
        private readonly static MailAddress DefaultSenderAddress;
        private readonly static ContentType DefaultContentType;
        private readonly static NetworkCredential DefaultCredentials;

        static Email()
        {            
            DefaultContentType = new ContentType("text/plain; charset=us-ascii");
            DefaultSenderAddress = new MailAddress("bolsadetalentosintec@gmail.com", "Bolsa de Talentos Intec");
            DefaultCredentials = new NetworkCredential("bolsadetalentosintec@gmail.com", "bolsa.talentos.123");
            DefaultSMTPClient = new SmtpClient("smtp.gmail.com", 587);
            //DefaultSMTPClient = new SmtpClient("smtp.gmail.com", 465);

            DefaultSMTPClient.EnableSsl = true;                        
            DefaultSMTPClient.UseDefaultCredentials = false;
        }

        public static Boolean SendMail(List<String> Recipients, List<string> AttatchmentPaths, String Subject, String MessageBody)
        {
            MailMessage Message = new MailMessage();
            DefaultSMTPClient.Credentials = DefaultCredentials;

            try
            {
                Message.From = DefaultSenderAddress;

                foreach (String Email in Recipients)
                    Message.To.Add(new MailAddress(Email));

                Message.Subject = Subject;
                Message.Body = MessageBody;
                Message.IsBodyHtml = true;

                if (AttatchmentPaths != null && AttatchmentPaths.Count != 0)
                    foreach (Attachment Att in CreateAttatchmentList(AttatchmentPaths))
                        Message.Attachments.Add(Att);

                DefaultSMTPClient.Send(Message);

                return true;
            }
            catch (SmtpFailedRecipientsException Ex)
            {
                throw Ex;
            }
            catch (SmtpException Ex)
            {
                throw Ex;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                Message.Dispose();
            }
        }

        public static List<Attachment> CreateAttatchmentList(List<String> Paths)
        {
            List<Attachment> ReturnValue = new List<Attachment>();

            ReturnValue.Add(new Attachment(@"D:\TextFile.txt", DefaultContentType));

            return ReturnValue;
        }

    }
}